<?php
namespace app\index\controller;

use app\index\model\Admin;
use think\facade\Request;
use think\captcha\Captcha;
use EasyWeChat\Factory;
use think\Db;

// app 接口端
class Api extends Base
{


    private $config = [
      'app_id' => '',
      'secret' => '',

      // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
      'response_type' => 'array',
      
      //...
    ];

    public function initialize()
    {
      $this->config['app_id'] = config('appid');
      $this->config['secret'] = config('app_secret');
    }


    // 上传文件
    public function uploadFile()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->move('uploads');
        if($info){
            $fileName = str_replace('\\', '/',$info->getSaveName());
            return apiSuccess(config('file_url').'/uploads/'.$fileName);
        }else{
            // 上传失败获取错误信息
            // return apiError('文件格式有误');
            echo $file->getError();
        }
    }

    // 判断是否登录
    public function isLogin() {
      $token = Request::header("token");
      if(empty($token)) {
        return apiSuccess(false);
      }
      $info = model('user')->where(['token'=>$token])->find();
      if($info){
        return apiSuccess(true);
      } else {
        return apiSuccess(false);
      }
    }

    // 微信授权登录 或者是绑定微信
    public function authLogin() {
      $param = Request::param();
      if (!$session = sessionKey($param['code'])) {
        return apiError('授权失败'); 
      }
      $openid = $session['openid'];
      $token = randString(32);
      $userModel = model('user');
      $info = $userModel->where(['openid'=>$openid])->find();
      if(!$info){
          $data = [
              'openid' => $openid,
              'token' => $token
          ];
          $userModel->save($data);
      } else {
          // 登录
          $userModel->where(['openid'=>$openid])->update(['token' => $token]);
      }
      return apiSuccess(['token'=>$token]); 
    }

    // 获取个人信息
    public function getInfo() {
      $param = Request::param();
      $info = model('user')->where(['id'=>$param['user_id']])->find();
      return apiSuccess($info); 
    }


    // 请求询问。。。。。
    public function getChatGPT() {
      $param = Request::param();
      //   return apiSuccess([
      //      'id' => onlyNumbers(),
      //     'user_id' => '',
      //     'issue' => $param['desc'],
      //     'answer' => $param['desc'].'呀',
      //     'create_time' => date("Y-m-d H:i:s")
      //   ]); 
      try {
          if(!isset($param['desc']) || empty($param['desc'])) {
            return apiError('请输入要提问的内容'); 
          }


          $app = Factory::miniProgram($this->config);
          if(!empty($param['desc'])) {
            $result = $app->content_security->checkText($param['desc']);
            if($result['errcode'] != 0) {
              return apiError('您发布的信息涉及敏感问题，大哥不要乱搞求求你了。。');
            }
          }
          

          $logsModel = model('logs');
          $userModel = model('user');
          $userInfo = $userModel->where(['id'=>$param['user_id']])->find();
        //   $num = $logsModel->where(['user_id'=>$param['user_id']])->count();
          if($userInfo['number'] < 1) {
            return apiError('你的接口次数已经用完，如果需要增加次数联系 v：fantasyo1559');
          }
          $response = $logsModel->getGpt($param['desc']);
          $res = json_decode($response, true);
          if(isset($res['error'])) {
            // $res['error']['message']
            return apiError('chatgpt接口被挤爆了，请你重新尝试一下，本次不计次数！'); 
          }
          $text = $res['choices'][0]['text'];
          $logsModel->save([
              'user_id'  =>  $param['user_id'],
              'issue' =>  $param['desc'],
              'answer' =>  $text
          ]);
          $id = $logsModel->id;
          $info = $logsModel->where(['id'=>$id])->find();
          // 减少次数
          $userModel->where(['id'=>$param['user_id']])->setDec('number', 1);
      } catch (\Throwable $th) {
          return apiError('服务异常，本次不计次数，管理员微：fantasyo1559');
      }
      return apiSuccess($info); 
    }

    // 获取聊天记录
    public function getGPTLog() {
      $param = Request::param();
      $list = model('logs')->getAllList($param['user_id']);
      return apiSuccess($list); 
    }





}
